//
//  DMInterstitialSceneInterceptor.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/1/15.
//

#import "DMInterstitialSceneInterceptor.h"
#import "../../Utils/Logger/IMLogUtils.h"

static NSString *const kSceneShowRecordsKey = @"DMInterstitialSceneShowRecords";
static NSString *const kSceneLastShowTimeKey = @"DMInterstitialSceneLastShowTime";
static NSString *const kSceneDailyCountKey = @"DMInterstitialSceneDailyCount";
static NSString *const kLastResetDateKey = @"DMInterstitialLastResetDate";

@interface DMInterstitialSceneInterceptor ()

@property (nonatomic, strong) NSUserDefaults *userDefaults;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;

@end

@implementation DMInterstitialSceneInterceptor

static DMInterstitialSceneInterceptor *_sharedInterceptor = nil;

+ (instancetype)sharedInterceptor {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInterceptor = [[self alloc] init];
    });
    return _sharedInterceptor;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _interceptorEnabled = YES;
        _minimumShowInterval = 30.0; // 30秒
        _maxDailyShows = 10; // 每日最大10次
        
        _userDefaults = [NSUserDefaults standardUserDefaults];
        _dateFormatter = [[NSDateFormatter alloc] init];
        _dateFormatter.dateFormat = @"yyyy-MM-dd";
        
        [self checkAndResetDailyCountIfNeeded];
        
        [IMLogUtils info:IMLogTagAd format:@"📱 [SceneInterceptor] 场景拦截器初始化完成"];
        [IMLogUtils info:IMLogTagAd format:@"📱 [SceneInterceptor] 最小展示间隔: %.0f秒", _minimumShowInterval];
        [IMLogUtils info:IMLogTagAd format:@"📱 [SceneInterceptor] 每日最大展示次数: %ld", (long)_maxDailyShows];
    }
    return self;
}

#pragma mark - Public Methods

- (BOOL)shouldInterceptScene:(NSString *)scene {
    if (!self.interceptorEnabled) {
        [IMLogUtils debug:IMLogTagAd format:@"📱 [SceneInterceptor] 拦截器已禁用，场景 %@ 不拦截", scene];
        return NO;
    }
    
    if (!scene || scene.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"📱 [SceneInterceptor] 场景参数无效，不拦截"];
        return NO;
    }
    
    // 检查是否为可拦截场景
    if (![DMInterstitialScenes isInterceptableScene:scene]) {
        [IMLogUtils debug:IMLogTagAd format:@"📱 [SceneInterceptor] 场景 %@ 不在可拦截列表中，不拦截", scene];
        return NO;
    }
    
    [self checkAndResetDailyCountIfNeeded];
    
    // 检查时间间隔
    if ([self isWithinMinimumInterval:scene]) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [SceneInterceptor] 🚫 场景 %@ 被时间间隔拦截（最小间隔: %.0f秒）", scene, self.minimumShowInterval];
        return YES;
    }
    
    // 检查每日展示次数
    if ([self isExceedingDailyLimit:scene]) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [SceneInterceptor] 🚫 场景 %@ 被每日次数限制拦截（最大次数: %ld）", scene, (long)self.maxDailyShows];
        return YES;
    }
    
    [IMLogUtils debug:IMLogTagAd format:@"📱 [SceneInterceptor] ✅ 场景 %@ 通过拦截检查", scene];
    return NO;
}

- (void)recordSceneShow:(NSString *)scene {
    if (!scene || scene.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"📱 [SceneInterceptor] 记录展示失败：场景参数无效"];
        return;
    }
    
    [self checkAndResetDailyCountIfNeeded];
    
    NSDate *now = [NSDate date];
    
    // 记录上次展示时间
    NSString *lastShowKey = [self lastShowTimeKeyForScene:scene];
    [self.userDefaults setObject:now forKey:lastShowKey];
    
    // 增加今日展示次数
    NSString *dailyCountKey = [self dailyCountKeyForScene:scene];
    NSInteger currentCount = [self.userDefaults integerForKey:dailyCountKey];
    [self.userDefaults setInteger:currentCount + 1 forKey:dailyCountKey];
    
    [self.userDefaults synchronize];
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneInterceptor] 📊 记录场景 %@ 展示，今日第 %ld 次", scene, (long)(currentCount + 1)];
}

- (NSInteger)getTodayShowCount:(NSString *)scene {
    if (!scene || scene.length == 0) {
        return 0;
    }
    
    [self checkAndResetDailyCountIfNeeded];
    
    NSString *dailyCountKey = [self dailyCountKeyForScene:scene];
    return [self.userDefaults integerForKey:dailyCountKey];
}

- (NSDate *)getLastShowTime:(NSString *)scene {
    if (!scene || scene.length == 0) {
        return nil;
    }
    
    NSString *lastShowKey = [self lastShowTimeKeyForScene:scene];
    return [self.userDefaults objectForKey:lastShowKey];
}

- (void)resetAllSceneRecords {
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneInterceptor] 🔄 重置所有场景展示记录"];
    
    NSArray *allScenes = [DMInterstitialScenes allInterstitialScenes];
    for (NSString *scene in allScenes) {
        [self resetSceneRecord:scene];
    }
    
    [self.userDefaults synchronize];
}

- (void)resetSceneRecord:(NSString *)scene {
    if (!scene || scene.length == 0) {
        return;
    }
    
    NSString *lastShowKey = [self lastShowTimeKeyForScene:scene];
    NSString *dailyCountKey = [self dailyCountKeyForScene:scene];
    
    [self.userDefaults removeObjectForKey:lastShowKey];
    [self.userDefaults removeObjectForKey:dailyCountKey];
    
    [IMLogUtils debug:IMLogTagAd format:@"📱 [SceneInterceptor] 重置场景 %@ 的展示记录", scene];
}

- (NSDictionary *)getSceneInterceptInfo:(NSString *)scene {
    if (!scene || scene.length == 0) {
        return @{};
    }
    
    NSDate *lastShowTime = [self getLastShowTime:scene];
    NSInteger todayCount = [self getTodayShowCount:scene];
    BOOL wouldIntercept = [self shouldInterceptScene:scene];
    
    NSTimeInterval timeSinceLastShow = 0;
    if (lastShowTime) {
        timeSinceLastShow = [[NSDate date] timeIntervalSinceDate:lastShowTime];
    }
    
    return @{
        @"scene": scene,
        @"interceptorEnabled": @(self.interceptorEnabled),
        @"wouldIntercept": @(wouldIntercept),
        @"lastShowTime": lastShowTime ?: [NSNull null],
        @"timeSinceLastShow": @(timeSinceLastShow),
        @"todayShowCount": @(todayCount),
        @"minimumShowInterval": @(self.minimumShowInterval),
        @"maxDailyShows": @(self.maxDailyShows),
        @"isInterceptableScene": @([DMInterstitialScenes isInterceptableScene:scene])
    };
}

#pragma mark - Private Methods

- (BOOL)isWithinMinimumInterval:(NSString *)scene {
    NSDate *lastShowTime = [self getLastShowTime:scene];
    if (!lastShowTime) {
        return NO; // 从未展示过，不拦截
    }
    
    NSTimeInterval timeSinceLastShow = [[NSDate date] timeIntervalSinceDate:lastShowTime];
    return timeSinceLastShow < self.minimumShowInterval;
}

- (BOOL)isExceedingDailyLimit:(NSString *)scene {
    NSInteger todayCount = [self getTodayShowCount:scene];
    return todayCount >= self.maxDailyShows;
}

- (void)checkAndResetDailyCountIfNeeded {
    NSString *today = [self.dateFormatter stringFromDate:[NSDate date]];
    NSString *lastResetDate = [self.userDefaults stringForKey:kLastResetDateKey];
    
    if (!lastResetDate || ![lastResetDate isEqualToString:today]) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [SceneInterceptor] 🗓️ 检测到新的一天，重置每日计数器"];
        [self resetDailyCounters];
        [self.userDefaults setObject:today forKey:kLastResetDateKey];
        [self.userDefaults synchronize];
    }
}

- (void)resetDailyCounters {
    NSArray *allScenes = [DMInterstitialScenes allInterstitialScenes];
    for (NSString *scene in allScenes) {
        NSString *dailyCountKey = [self dailyCountKeyForScene:scene];
        [self.userDefaults removeObjectForKey:dailyCountKey];
    }
}

- (NSString *)lastShowTimeKeyForScene:(NSString *)scene {
    return [NSString stringWithFormat:@"%@_%@", kSceneLastShowTimeKey, scene];
}

- (NSString *)dailyCountKeyForScene:(NSString *)scene {
    return [NSString stringWithFormat:@"%@_%@", kSceneDailyCountKey, scene];
}

#pragma mark - Setters

- (void)setInterceptorEnabled:(BOOL)interceptorEnabled {
    _interceptorEnabled = interceptorEnabled;
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneInterceptor] 拦截器状态: %@", interceptorEnabled ? @"启用" : @"禁用"];
}

- (void)setMinimumShowInterval:(NSTimeInterval)minimumShowInterval {
    _minimumShowInterval = minimumShowInterval;
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneInterceptor] 最小展示间隔更新为: %.0f秒", minimumShowInterval];
}

- (void)setMaxDailyShows:(NSInteger)maxDailyShows {
    _maxDailyShows = maxDailyShows;
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneInterceptor] 每日最大展示次数更新为: %ld", (long)maxDailyShows];
}

@end